<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级名称" prop="className">
        <el-input
            v-model="queryParams.className"
            placeholder="请输入班级名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学院名称" prop="collegeId">
        <el-select v-model="queryParams.collegeId" placeholder="请选择学院" clearable style="width: 150px;">
          <el-option
              v-for="item in collegeList"
              :key="item.collegeId"
              :label="item.collegeName"
              :value="item.collegeId"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--增加辅导员姓名宽度，而不是下拉框宽度-->
      <el-form-item label="辅导员姓名" prop="headTeacher">
        <el-input
            v-model="queryParams.headTeacher"
            placeholder="请输入辅导员姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
            v-model="queryParams.contactPhone"
            placeholder="请输入班主任联系电话"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="classStatus">
        <el-select v-model="queryParams.classStatus" placeholder="请选择状态" clearable style="width: 150px;"  >
          <el-option
              v-for="dict in class_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['college:administrativeClass:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['college:administrativeClass:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['college:administrativeClass:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['college:administrativeClass:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="administrativeClassList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="开课院校" align="center">
        <template #default="scope">
          {{ getCollegeName(scope.row.collegeId) }}
        </template>
      </el-table-column>
      <el-table-column label="当前班级人数" align="center" prop="studentCount" />
      <el-table-column label="班主任/辅导员姓名" align="center" prop="headTeacher" />
      <el-table-column label="班主任联系电话" align="center" prop="contactPhone" />
      <el-table-column label="状态" align="center" prop="classStatus">
        <template #default="scope">
          <dict-tag :options="class_status" :value="scope.row.classStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="addStudent(scope.row)" v-hasPermi="['college:administrativeClass:edit']">添加学生</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['college:administrativeClass:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['college:administrativeClass:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--添加学生页面-->
    <el-dialog title="添加学生" v-model="addStudentOpen" width="1200px" append-to-body class="admin-class-dialog">
      <!-- 培养方案 -->
      <div class="form-section mt-16">
        <h4 class="section-title">培养方案管理</h4>
        <el-form-item label="培养方案">
          <div class="training-program-container">
            <div class="search-container" style="display: flex; gap: 16px;">
              <el-input v-model="form.programSearch" placeholder="输入培养方案名称/编号搜索" @keyup.enter="searchTrainingPrograms" style="width: 500px" class="search-input"/>
              <el-button type="primary" @click="searchTrainingPrograms" :loading="searchLoading" class="search-button">
                搜索方案
              </el-button>
            </div>
            <!-- 搜索结果 -->
            <div v-if="searchTrainingProgramList.length > 0" class="search-results mt-8">
              <div v-for="program in searchTrainingProgramList" :key="program.id" class="result-item" @click="selectTrainingProgram(program)">
                <span class="name">{{ program.name }}</span>
                <div class="meta">
                  编号：{{ program.programCode }}
                </div>
              </div>
            </div>
          </div>
          <!-- 已选培养方案列表 -->
          <div class="selected-courses mt-16">
            <el-table :data="form.trainingPrograms" border max-height="300" style="width: 100%;" class="custom-table">
              <el-table-column label="方案编号" prop="programCode" width="150" />
              <el-table-column label="方案名称" prop="name" width="250" />
              <el-table-column label="方案类型" width="150">
                <template #default="scope">
                  <dict-tag :options="culture_program_type" :value="scope.row.cultureProgramType"/>
                </template>
              </el-table-column>
              <el-table-column label="总学分" prop="totalCredits" width="100" />
              <el-table-column label="适用年级" width="120">
                <template #default="scope">
                  <dict-tag :options="grade" :value="scope.row.grade"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button type="danger" icon="Delete" size="mini" @click="removeTrainingProgram(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </div>
      <div class="student-list-btn-container">
        <el-button type="primary" @click="addStudentManger">
          查询学生名单
        </el-button>
      </div>
      <!-- 展示培养方案对应的学生名单 -->
      <div v-if="form.students && form.students.length > 0" class="student-list-container mt-16">
        <div class="student-list-header">
          <h4 class="section-title">学生名单</h4>
          <div class="tip-message" v-if="form.students.some(student => student.studentBj)">
            <el-tag type="info" size="small">
              提示：已分配行政班的学生（班级名称非空）无法重复分配
            </el-tag>
          </div>
        </div>
        <el-table ref="studentTableRef" :data="form.students" border style="width: 100%;" class="custom-table" @selection-change="handleStudentSelectionChange" @select-all="handleSelectAll">
          <el-table-column type="selection" width="50" align="center" :selectable="(row) => !row.studentBj">
            <template #default="{ row }">
              <el-checkbox v-model="row.__selected" :disabled="row.studentBj&& !row.isEditing" :class="{ 'is-assigned': row.studentBj && !row.isEditing }"/>
            </template>
          </el-table-column>
          <el-table-column label="学号" prop="studentId" />
          <el-table-column label="姓名" prop="studentName" />
          <el-table-column label="性别" prop="studentSex" />
          <el-table-column label="联系电话" prop="studentJdfs" />
          <el-table-column label="培养方案" prop="studentZy" />
          <el-table-column label="班级名称" align="center">
            <template #default="scope">
              {{ getAdministrativeClassName(scope.row.studentBj) || scope.row.studentBj }}
            </template>
          </el-table-column>
          <!--添加操作栏-->
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                  type="primary"
                  size="mini"
                  @click="toggleEditMode(scope.row)"
              :disabled="!scope.row.studentBj"
              >
              修改行政班
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddStudent">确 定</el-button>
          <el-button @click="cancelAddStudent">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或 修改行政班管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="administrativeClassRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级名称" prop="className">
              <el-input v-model="form.className" placeholder="请输入班级名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开课院校" prop="collegeId">
              <el-select v-model="form.collegeId" placeholder="请选择开课院校" style="width: 100%">
                <el-option
                    v-for="college in collegeList"
                    :key="college.collegeId"
                    :label="college.collegeName"
                    :value="college.collegeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="辅导员姓名" prop="headTeacher">
              <el-input v-model="form.headTeacher" placeholder="请输入辅导员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级人数">
              <el-input v-model="form.studentCount" placeholder="请输入班级人数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="classStatus">
              <el-radio-group v-model="form.classStatus">
                <el-radio v-for="dict in class_status" :key="dict.value" :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>
<script setup name="AdministrativeClass">
import { ref, reactive, computed, nextTick } from 'vue';
import { listAdministrativeClass, getAdministrativeClass, delAdministrativeClass, addAdministrativeClass, updateAdministrativeClass } from "@/api/college/administrativeClass";
import { listCollege } from "@/api/college/college";
import { listTrainingManagement } from "@/api/trainingManagement/trainingManagement";
import { loadAllParams } from "@/api/page.js";
import { batchAddClassTrainingLink, listClassTrainingLink } from '@/api/college/classTrainingLink';
import { listStudentManger } from "@/api/student/studentManger";
const selectedStudentIds = ref(new Set());
const isSelectingAll = ref(false);

import axios from "axios";
import {assignStudentsToClass} from "../../../api/college/administrativeClass.js";
const { proxy } = getCurrentInstance();
const { class_status, culture_program_type, grade } = proxy.useDict(
    'class_status',
    'culture_program_type',
    'grade'
);

// 表单数据
const form = ref({
  id: null,
  className: "",
  collegeId: "",
  studentCount: "",
  headTeacher: "",
  contactPhone: "",
  classStatus: "",
  programSearch: '',
  trainingPrograms: [],
  students: [],
  isConfirmed: false,
  adminClassId: null
});
const formList = ref([]);
const searchTrainingProgramList = ref([]);
const administrativeClassList = ref([]);
const open = ref(false);
const addStudentOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const searchLoading = ref(false);

// 存储相关状态
const isDataStored = ref(false);
const storageKey = 'administrative_classes_v1';
const selectedClassForAssign = ref(null);
const selectedStudents = ref([]);
const availableClasses = ref([]);
const originalFormData = ref([]);

// 搜索参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10000,
    className: null,
    collegeId: null,
    headTeacher: null,
    contactPhone: null,
    classStatus: null
  }
});
const { queryParams } = toRefs(data);

// 计算属性
const buttonText = computed(() => form.value.isConfirmed ? "修改" : "确认行政班添加完成");
const buttonType = computed(() => form.value.isConfirmed ? "primary" : "success");
const isFormDisabled = computed(() => form.value.isConfirmed);

// 获取可用班级列表
const getAvailableClasses = () => {
  try {
    const storedData = localStorage.getItem(storageKey);
    if (storedData) {
      const parsedData = JSON.parse(storedData);
      if (Array.isArray(parsedData)) {
        return parsedData.map(item => ({
          id: item.id || `class_${Date.now()}_${Math.random().toString(36).substr(2, 4)}`,
          className: item.className,
          collegeId: item.collegeId
        }));
      }
      if (typeof parsedData === 'object') {
        return [{
          id: parsedData.id || `class_${Date.now()}_${Math.random().toString(36).substr(2, 4)}`,
          className: parsedData.className,
          collegeId: parsedData.collegeId
        }];
      }
    }
    return [];
  } catch (error) {
    console.error('获取存储的行政班数据失败:', error);
    return [];
  }
};
// 重置表单
function reset() {
  form.value = {
    id: null,
    className: "",
    collegeId: "",
    studentCount: "",
    headTeacher: "",
    contactPhone: "",
    classStatus: "",
    programSearch: '',
    trainingPrograms: [],
    students: [],
    isConfirmed: false
  };
  formList.value = getAvailableClasses().length > 0 ? getAvailableClasses() : [{
    className: "",
    collegeId: "",
    studentCount: "",
    headTeacher: "",
    contactPhone: "",
    classStatus: ""
  }];
  proxy.resetForm("administrativeClassRef");
}

// 查询列表
function getList() {
  loading.value = true;
  listAdministrativeClass(queryParams.value).then(response => {
    administrativeClassList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置搜索
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 选择变化
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增
function handleAdd() {
  reset();
  localStorage.removeItem(storageKey);
  form.value = {
    id: null,
    className: "",
    collegeId: "",
    studentCount: "",
    headTeacher: "",
    contactPhone: "",
    classStatus: "",
    trainingPrograms: [],
    students: [],
    isConfirmed: false
  };
  formList.value = [{
    className: "",
    collegeId: "",
    studentCount: "",
    headTeacher: "",
    contactPhone: "",
    classStatus: ""
  }];
  availableClasses.value = getAvailableClasses();
  open.value = true;
  title.value = "添加行政班管理";
  isDataStored.value = false;
  form.value.isConfirmed = false;
}

// 删除
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除行政班管理编号为"' + _ids + '"的数据项？').then(() => {
    return delAdministrativeClass(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 导出
function handleExport() {
  proxy.download('college/administrativeClass/export', {
    ...queryParams.value
  }, `administrativeClass_${new Date().getTime()}.xlsx`)
}

// 获取学院列表
const collegeList = ref([]);

function getCollegeList() {
  listCollege({}).then(response => {
    collegeList.value = response.rows;
  });
}

// 通过学院ID获取名称
const getCollegeName = (id) => {
  if (id) {
    const college = collegeList.value.find(item => item.collegeId === id);
    return college ? college.collegeName : '';
  }
  return '';
}

// 搜索培养方案
const searchTrainingPrograms = async () => {
  const searchKey = form.value.programSearch?.trim();
  if (!searchKey) {
    proxy.$modal.msgWarning("请输入培养方案名称关键词");
    searchTrainingProgramList.value = [];
    searchLoading.value = false;
    return;
  }
  try {
    searchLoading.value = true;
    searchTrainingProgramList.value = [];
    const res = await listTrainingManagement({
      name: searchKey,
      pageSize: 100
    });
    if (res && res.rows && Array.isArray(res.rows)) {
      searchTrainingProgramList.value = res.rows.map(item => ({
        id: item.id,
        programCode: item.programCode,
        name: item.name,
        cultureProgramType: item.cultureProgramType,
        totalCredits: item.totalCredits,
        grade: item.grade
      }));
    } else {
      proxy.$modal.msgInfo("未找到匹配的培养方案");
    }
  } catch (e) {
    proxy.$modal.msgError('培养方案搜索失败');
    console.error('搜索失败:', e);
  } finally {
    searchLoading.value = false;
  }
};

// 选择培养方案
const selectTrainingProgram = (program) => {
  if (form.value.trainingPrograms.some(p => p.id === program.id)) {
    proxy.$modal.msgWarning('该方案已添加');
    return;
  }
  form.value.trainingPrograms.push({
    id: program.id,
    programCode: program.programCode,
    name: program.name,
    cultureProgramType: program.cultureProgramType,
    totalCredits: program.totalCredits,
    grade: program.grade
  });
  form.value.programSearch = '';
  searchTrainingProgramList.value = [];
};

// 查询学生名单
const addStudentManger = async () => {
  console.log("选中的培养方案:", form.value.trainingPrograms);
  if (form.value.trainingPrograms.length === 0) {
    proxy.$modal.msgWarning('没有选择任何培养方案');
    return;
  }
  form.value.students = [];
  for (const program of form.value.trainingPrograms) {
    if (program.id) {
      try {
        // 关键修改：添加pageSize参数，获取该培养方案下的所有学生
        const studentList = await listStudentManger({
          trainingProgramId: program.id,
          pageSize: 1000  // 设置足够大的pageSize，覆盖默认10条限制
        });
        console.log(`查询到的学生名单 (方案ID: ${program.id}):`, studentList);

        if (studentList && studentList.rows && Array.isArray(studentList.rows)) {
          form.value.students = [...form.value.students, ...studentList.rows];
          console.log("合并后的学生名单:", form.value.students);
        }
      } catch (error) {
        console.error(`获取培养方案ID为${program.id}的学生名单失败:`, error);
        proxy.$modal.msgError(`获取学生名单失败 (方案ID: ${program.id})`);
      }
    } else {
      console.error("培养方案ID为空，无法查询学生名单");
      proxy.$modal.msgWarning("培养方案ID为空");
    }
  }
};

// 删除培养方案
const removeTrainingProgram = (index) => {
  form.value.trainingPrograms.splice(index, 1);
};

// 提交行政班表单
const submitForm = () => {
  proxy.$refs["administrativeClassRef"].validate(valid => {
    if (valid) {
      const submitData = {...form.value};
      const isUpdate = submitData.id !== null;
      loading.value = true;

      const handleAdminClass = async () => {
        if (isUpdate) {
          await updateAdministrativeClass(submitData);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          const res = await addAdministrativeClass(submitData);
          submitData.id = res.data.id;
          proxy.$modal.msgSuccess("新增成功");
        }
      };

      const handleTrainingLinks = async () => {
        const programIds = submitData.trainingPrograms.map(p => p.id);
        if (programIds.length > 0) {
          const links = programIds.map(programId => ({
            administrativeClassId: submitData.id,
            trainingProgramId: programId
          }));
          try {
            await batchAddClassTrainingLink(links);
          } catch (error) {
            console.error('关联培养方案失败:', error);
            proxy.$modal.msgError("关联培养方案失败: " + (error.message || "未知错误"));
            throw error;
          }
        }
      };

      handleAdminClass()
          .then(handleTrainingLinks)
          .then(() => {
            open.value = false;
            getList();
          })
          .catch(error => {
            console.error('提交失败:', error);
            proxy.$modal.msgError("操作失败: " + (error.message || "未知错误"));
          })
          .finally(() => {
            loading.value = false;
          });
    }
  });
};
// 打开对话框时设置 adminClassId
const openAddStudentDialog = (adminClassId) => {
  form.value.adminClassId = adminClassId;
  addStudentOpen.value = true;
};
// 添加学生页面提交
const submitAddStudent = async () => {
  const studentIds = Array.from(selectedStudentIds.value);
  console.log("提交的学生ID列表:", studentIds);

  if (studentIds.length === 0) {
    proxy.$message.warning("请至少选择一名学生");
    return;
  }

  const adminClassId = form.value.adminClassId;
  if (!adminClassId) {
    proxy.$message.error("行政班ID不能为空");
    return;
  }

  const params = {
    adminClassId,
    studentIds
  };

  try {
    const response = await assignStudentsToClass(params);
    if (response.code === 200) {
      proxy.$message.success("学生分配成功");
      closeDialog(addStudentOpen);
      getList();
    } else {
      proxy.$message.error(`分配失败: ${response.msg || "未知错误"}`);
    }
  } catch (error) {
    console.error("分配请求异常:", error);
    proxy.$message.error(`分配失败: ${error.message || "网络错误"}`);
  }
};
// 添加学生
const addStudent = (row) => {
  console.log('添加学生按钮被点击，班级ID:', row.id);
  nextTick(() => {
    // 调用正确的函数传递行政班ID
    openAddStudentDialog(row.id);
  });
}

// 修改
const handleUpdate = async (row) => {
  reset();
  const classId = row.id;
  loading.value = true;
  try {
    const adminClassRes = await getAdministrativeClass(classId);
    if (!adminClassRes || !adminClassRes.data) {
      return proxy.$modal.msgError("行政班信息获取失败");
    }
    adminClassRes.data.students = adminClassRes.data.students || [];
    form.value = {
      ...adminClassRes.data,
      students: adminClassRes.data.students
    };
    try {
      const linksRes = await listClassTrainingLink({administrativeClassId: classId});
      if (!linksRes || !linksRes.rows || linksRes.rows.length === 0) {
        proxy.$modal.msgWarning("未找到关联的培养方案");
        form.value = {...adminClassRes.data, trainingPrograms: []};
        return;
      }
      const programIds = linksRes.rows.map(link => link.trainingProgramId);
      if (programIds.length > 0) {
        const programsRes = await listTrainingManagement({ids: programIds});
        if (programsRes && programsRes.rows) {
          form.value = {
            ...adminClassRes.data,
            trainingPrograms: programsRes.rows.filter(program => programIds.includes(program.id))
          };
        } else {
          form.value = {
            ...adminClassRes.data,
            trainingPrograms: []
          };
          proxy.$modal.msgWarning("未找到相关的培养方案");
        }
      } else {
        form.value = {
          ...adminClassRes.data,
          trainingPrograms: []
        };
        proxy.$modal.msgWarning("该行政班未关联任何培养方案");
      }
    } catch (linkError) {
      proxy.$modal.msgError("中间表接口调用失败，请联系管理员");
    }
    open.value = true;
    title.value = "修改行政班管理";
    availableClasses.value = getAvailableClasses();
  } catch (error) {
    proxy.$modal.msgError("加载数据失败，请检查网络或联系管理员");
  } finally {
    loading.value = false;
  }
};
// 关闭对话框通用方法
const closeDialog = (dialogRef) => {
  dialogRef.value = false;
  if (dialogRef === addStudentOpen) {
    form.value.programSearch = '';
    form.value.trainingPrograms = [];
    form.value.students = [];
    searchTrainingProgramList.value = [];
  } else if (dialogRef === open) {
    reset();
  }
};
// 取消按钮处理
const cancel = () => {
  closeDialog(open);
};
// 取消添加学生
const cancelAddStudent = () => {
  closeDialog(addStudentOpen);
};
// 获取培养方案
const TrainingProgramList = ref([]);

function getTrainingProgramList() {
  listTrainingManagement({loadAllParams}).then(response => {
    TrainingProgramList.value = response.rows;
  });
}
// 清空存储
const clearStoredClasses = () => {
  proxy.$confirm('确定要清空已存储的行政班数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem(storageKey);
    isDataStored.value = false;
    proxy.$message.success('已清空存储的行政班数据');
  }).catch(() => {
  });
};
//根据行政班ID获取行政班名称
const getAdministrativeClassName = (classId) => {
  //打印获取到的行政班ID
  console.log('获取的行政班ID:', classId);
  if (!classId || !administrativeClassList.value) {
    return '';
  }
  const classItem = administrativeClassList.value.find(
      item => item.id === classId
  );
  return classItem?.className || '';
};

// 切换学生的编辑模式
const handleStudentSelectionChange = (selection) => {
  // 清空当前页未选中的学生
  form.value.students.forEach(student => {
    if (!student.studentBj && !selection.some(s => s.id === student.id)) {
      selectedStudentIds.value.delete(student.id);
    }
  });

  // 添加当前页选中的学生
  selection.forEach(student => {
    if (!student.studentBj) {
      selectedStudentIds.value.add(student.id);
    }
  });

  // 更新全选按钮状态
  isSelectingAll.value =
      selection.length > 0 &&
      selection.length === form.value.students.filter(s => !s.studentBj).length;

  console.log('当前选中学生ID:', Array.from(selectedStudentIds.value));
};
const handleSelectAll = (selection) => {
  // 筛选出所有可以被选中的学生（排除已分配班级的学生）
  const availableStudents = form.value.students.filter(s => !s.studentBj);
  if (availableStudents.length === 0) return;

  // 获取表格实例（确保ref正确）
  const table = proxy.$refs.studentTableRef;
  if (!table) return;

  if (selection.length > 0) {
    // 全选操作：选中所有可选学生
    availableStudents.forEach(student => {
      // 1. 更新全局选中集合
      selectedStudentIds.value.add(student.id);
      // 2. 手动触发表格行选中（同步UI）
      table.toggleRowSelection(student, true);
    });
    isSelectingAll.value = true;
  } else {
    // 取消全选：取消所有可选学生的选中状态
    availableStudents.forEach(student => {
      // 1. 从全局集合中移除
      selectedStudentIds.value.delete(student.id);
      // 2. 手动取消表格行选中（同步UI）
      table.toggleRowSelection(student, false);
    });
    isSelectingAll.value = false;
  }

  console.log('全选操作后选中学生ID:', Array.from(selectedStudentIds.value));
};
// 监听学生数据变化，重新回显选中状态
watch(
    () => form.value.students,
    (newStudents) => {
      nextTick(() => {
        const table = proxy.$refs.studentTableRef;
        if (!table || !newStudents.length) return;

        // 筛选可选学生
        const availableStudents = newStudents.filter(s => !s.studentBj);
        availableStudents.forEach(student => {
          // 根据全局集合状态，更新表格行选中状态
          const isSelected = selectedStudentIds.value.has(student.id);
          table.toggleRowSelection(student, isSelected);
        });

        // 更新全选状态
        const selectedCount = availableStudents.filter(s => selectedStudentIds.value.has(s.id)).length;
        isSelectingAll.value = selectedCount > 0 && selectedCount === availableStudents.length;
      });
    },
    { deep: true }
);
// 初始化
getTrainingProgramList();
getCollegeList();
getList();
</script>
<style scoped>
/* 基础样式重置 */
:deep(.el-dialog__footer) {
  display: flex !important;
  justify-content: center !important;
  padding: 16px 24px !important;
}
:deep(.is-assigned .el-checkbox__inner) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  cursor: not-allowed;
}

:deep(.is-assigned .el-checkbox__inner:hover) {
  border-color: #dcdfe6;
  background-color: #f5f7fa;
}

:deep(.is-assigned .el-checkbox__inner::after) {
  display: none;
}
/* 学生名单标题区域 */
.student-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
/* 行政班管理样式 */
.admin-class-dialog {
  .form-section {
    background-color: #f9f9f9;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 20px;
  }
  .section-title {
    color: #222;
    font-size: 16px;
    margin-bottom: 12px;
    padding-left: 8px;
    border-left: 3px solid #409EFF;
  }
  .el-row + .el-row {
    margin-top: 12px;
  }
  .training-program-container {
    position: relative;
  }
  .search-container {
    position: relative;
    width: 100%;
    max-width: 600px;
  }
  .search-input {
    transition: all 0.3s ease;
  }
  .search-button {
    margin-left: 12px;
    padding: 8px 20px;
  }
  .search-results {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    z-index: 1000;
    background: white;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    max-height: 300px;
    overflow-y: auto;
    margin-top: 8px;
  }
  .result-item {
    padding: 10px 16px;
    cursor: pointer;
    transition: background 0.3s;
    display: flex;
    flex-direction: column;
  }
  .result-item:hover {
    background-color: #f5f7fa;
  }
  .result-item .name {
    font-weight: 500;
  }
  .result-item .meta {
    font-size: 13px;
    color: #8492a6;
    margin-top: 4px;
  }
  .custom-table {
    border-radius: 4px;
    overflow: hidden;
  }
  .full-width {
    width: 100%;
  }
  .radio-group .el-radio {
    margin-right: 16px;
  }
  @media (max-width: 768px) {
    .el-col-12 {
      width: 100% !important;
      margin-bottom: 12px;
    }
  }
}
/* 公共样式 */
.section-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}
.student-list-btn-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}
.student-list-btn-container .el-button {
  min-width: 120px;
  padding: 10px 20px;
  font-size: 14px;
}
.search-container {
  display: flex;
  align-items: center;
  gap: 16px;
}
.search-input {
  flex: 1;
}
:deep(.el-table__header) th {
  background-color: #f5f7fa;
  font-weight: bold;
}
:deep(.el-table__row) td {
  padding: 12px 0;
}
:deep(.el-dialog__body) {
  padding: 20px 25px;
}
</style>